package com.tl.bootmeter.config;


import com.tl.bootmeter.pojo.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@Component
public class UrlInterceptor implements HandlerInterceptor {

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        // TODO Auto-generated method stub
        String uri = request.getRequestURI();
        HttpSession session = request.getSession();
        System.out.println("拦截器---------"+uri);
        User userPower = (User) session.getAttribute("user");
        System.out.println("拦截器---------"+userPower);
        //只对动态资源进行拦截
        if(uri.endsWith(".html") || uri.endsWith(".do")){
            //对动态资源中的首页资源、登陆资源进行放行
            if(uri.indexOf("/BootMeter/") != -1
                    || uri.indexOf("login.html") != -1
                    || uri.indexOf("login") != -1
                    || uri.indexOf("register") != -1
                    || uri.indexOf("selectAllDistrict") != -1
                    || uri.indexOf("selectByDistrictIdStation") != -1
                    || uri.indexOf("selectUserByuname") != -1
            ){
                return true;
            }else{
                boolean flag = false;
                //如果有用户信息,说明已经登陆,进行放行
                if(userPower != null){
                    flag = true;
                }
                if(!flag){
                    System.out.println("拦截器---------进行拦截");
                    request.setAttribute("message", "请登录后进行访问！");
                    request.getRequestDispatcher("/login.html").forward(request, response);
                }
                return flag;
            }
        }
        return true;
    }

}
